#include "app_message.h"
#include "stddef.h"
static int hex_to_int(char c){
    if(c >= '0' && c <= '9')
        return c - '0';
    else if(c >= 'a' && c <= 'f')
        return c - 'a' + 10;
    else if(c >= 'A' && c <= 'F')
        return c - 'A' + 10;
    else
        return -1;
}

static char *hex_to_binary(char *hex,int *binLength){
    int hex_len = strlen(hex);
    int byte_len = hex_len / 2+1;
    char *binary=(char*)malloc(byte_len);
    int bin_index=0;
    
    for(int i = 0;i < hex_len;i+=2){
        binary[bin_index++]=hex_to_int(hex[i])*16+hex_to_int(hex[i+1]);
    }
    binary[bin_index-1]='\0';
    *binLength=byte_len-1;
    return 
}

static char *binary_to_hex(char *binary_arr,int binary_len){
    int hex_len = binary_len*2+1;
    char *hex_str=(char*)malloc(hex_len);
    
    for(int i = 0;i < binary_len;i++){
        sprintf(&hex_str[i*2],"%02x",binary_arr[i]);
    }

    hex_str[hex_len-1]='\0';
    return hex_str;

}

/**
 * @brief  通过二进制字符串初始化消息对象
 */
Message * app_messsage_initByBinary(char *binary,int len)
{
    Message *message = (Message *)malloc(sizeof(Message));
    memset(message,0,sizeof(Message));
    memcpy(&message->conn_type,binary,1);
    memcpy(&message->id_len,binary+1,1);
    memcpy(&message->msg_len,binary+2,1);
    if(len!=message->id_len+message->msg_len+3){
        log_error("message length error");
        free(message);
        return NULL;
    }
    message->payload=(char *)malloc(message->msg_len+message->id_len);
    memcpy(message->payload,binary+3,message->msg_len+message->id_len);

    return message;
}

Message * app_messsage_initByJson(char *json){
    cJSON
}

int app_message_toBinary(Message *message,char *binary,int len){

}
int app_message_toJson(Message *message,char *json,int len)
{

}
void app_message_free(Message *message){

}